package com.apestech.framework.xml.table.node;

import com.apestech.formwork.xml.XmlQuery;
import com.apestech.framework.xml.pub.core.ElementUtil;
import com.apestech.framework.xml.table.modul.Tables;
import org.dom4j.Element;
import java.util.List;

/**
 * @author hup
 * @create 2018-12-28-14:59
 */
public class NodeTables extends ElementUtil {
    private Element node;
    private Tables table=new Tables();
    private String key;
    private XmlQuery xmlQuery;

    public NodeTables(Element node, XmlQuery xmlQuery){
        this.xmlQuery=xmlQuery;
        this.node=node;
    }

    public void setTable(Tables table) {
        this.table = table;
    }

    public Tables getTable() {
        return table;
    }

    public void getAllDb() throws Exception {
        key=node.attributeValue("id");
        table.setId(key);
        List<?> list=node.content();
        int len=list.size();
        for(int i=0; i<len; i++){
            String scalss=list.get(i).getClass().getName();
            if(scalss.equals("org.dom4j.tree.DefaultElement")){
                getDbList((Element) list.get(i));
            }
        }
    }

    private void getDbList(Element eml) throws Exception {
        String name=eml.getName();
        switch (name){
            case "table":{
                table.addTabInfo(key, getNodeAttr(eml).getJSONObject("attrNode"));
                break;
            }
            case "field":{
                table.addField(key, getNodeAttr(eml).getJSONObject("attrNode"));
                break;
            }
            case "seqKey":{
                table.setSeq(getNodeAttr(eml).getJSONObject("attrNode"));
                break;
            }
            case "uniqueIndex":{
                table.addUniqueIndex(key, getNodeAttr(eml).getJSONObject("attrNode"));
                break;
            }
            case "tables":{
                String id=eml.attributeValue("id");
                String cname=eml.attributeValue("name");
                if(cname!=null) cname=cname.toUpperCase();
                if(id==null) id=cname;
                String masterTab=eml.attributeValue("masterTab");
                String masterTabName=eml.attributeValue("masterTabName");
                if(masterTabName!=null) masterTabName=masterTabName.toUpperCase();
                if(masterTab==null) masterTab=masterTabName;
                if(masterTab!=null){
                    table.addMasterTab(id, cname, masterTab,masterTabName);
                } else{
                    table.setMaster(id);
                    table.addMasterTab(id, cname,"1", "1");
                }
                eml=xmlQuery.getNode(id, "tables");
                if(eml!=null){
                    NodeTables t=new NodeTables(eml, xmlQuery);
                    t.setTable(table);
                    t.getAllDb();
                    table=t.getTable();
                }
                break;
            }
        }
    }
}
